package bjut.core.zookeeper;


import bjut.core.extension.ExtensionLoader;
import bjut.core.config.ProviderConfig;
import bjut.core.interfaces.ServiceProvider;
import bjut.core.interfaces.ServiceRegistry;
import bjut.core.netty.ZRpcNettyServer;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/20 22:52
 */
public class ZkServiceProviderImpl implements ServiceProvider {

    private final ConcurrentHashMap<String, Object> registeredServiceMap;
    private final Set<String> registeredSet;
    private final ServiceRegistry serviceRegistry;

    public ZkServiceProviderImpl() {
        registeredServiceMap = new ConcurrentHashMap<>();
        registeredSet = ConcurrentHashMap.newKeySet();
        serviceRegistry = ExtensionLoader.getExtensionLoader(ServiceRegistry.class).getExtension("zookeeper");
    }

    @Override
    public void registerService(ProviderConfig providerConfig) {

        try {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            addService(providerConfig);
            serviceRegistry.registerService(providerConfig.getRpcServiceName(), new InetSocketAddress(hostAddress, ZRpcNettyServer.PORT));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void addService(ProviderConfig providerConfig) {

        String rpcServiceName = providerConfig.getRpcServiceName();
        if (registeredSet.contains(rpcServiceName)) {
            return;
        }
        registeredSet.add(rpcServiceName);
        registeredServiceMap.put(rpcServiceName, providerConfig.getService());
    }

    @Override
    public Object getService(String serviceName) {

        Object service = registeredServiceMap.get(serviceName);

        if (null == service) {
            throw new RuntimeException("no such service");
        }
        return service;
    }
}
